<template>
    <div id="test">
        <!-- 步骤条模块 -->
        <div class="divStep">
            <el-steps :active="processNum" finish-status="success" align-center>
                <!-- <el-step title="开始" ></el-step> -->
                <el-step title="上传压缩包"></el-step>
                <el-step title="文件分析" description="IDA处理二进制文件"></el-step>
                <el-step title="模型检测"></el-step>
                <el-step title="漏洞检测报告"></el-step>
                <!-- <el-step title="结束"></el-step> -->
            </el-steps>
        </div>

        <!-- 按钮模块 分步执行-->
        <!-- <div class="divButton">
				<div>
					<el-button   @click="selectModel" :loading="loadingData[5].loading" >{{loadingData[5].text}}</el-button>
				</div>
				<div>
					<el-button  :type="buttonType(0)" @click="uploadFile" :loading="loadingData[0].loading" v-bind:disabled="dis[0]" >{{loadingData[0].text}}</el-button>
				</div>
				<div>
					<el-button  :type="buttonType(1)" @click="socket(3)" :loading="loadingData[1].loading" v-bind:disabled="dis[1]">{{loadingData[1].text}}</el-button>
				</div>
				<div>
					<el-button  :type="buttonType(2)" @click="socket(4)" :loading="loadingData[2].loading" v-bind:disabled="dis[2]">{{loadingData[2].text}}</el-button>
				</div>
				<div>
					<el-button  :type="buttonType(3)" @click="socket(5)" :loading="loadingData[3].loading" v-bind:disabled="dis[3]">{{loadingData[3].text}}</el-button>
				</div>
				<div>
					<el-button  :type="buttonType(4)" @click="result" :loading="loadingData[4].loading" v-bind:disabled="dis[4]">{{loadingData[4].text}}</el-button>
				</div>
			</div> -->

        <!--上传文件组件-->
        <div class="divUpload">
            <h1>
                <div class="divUploadDemo">
                    <el-upload 
                        class="upload-demo" 
                        drag 
                        action="http://localhost:8080/vulnerability/VulUpload/upload"
                        :auto-upload="false"
                        ref="uploadRef"
                        :on-success="uploadSuccess"
                        multiple>
                        <i class="el-icon-upload"></i>
                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                        <div class="el-upload__tip" slot="tip">请将用于测试的二进制文件直接打包并在此处上传<br>（注：压缩包格式需为.zip或.tar）</div>
                    </el-upload>
                    <br><el-button type="primary" @click="uploadFile">开始检测<i
                            class="el-icon-upload el-icon--right"></i></el-button>
                    <br><el-button class="buttonDiv">GMN+</el-button>
                    <el-button class="buttonDiv">OFST</el-button>
                    <a href="http://localhost:8080/vulnerability/VulUpload/download">Click me to download</a>
                </div>
            </h1>
        </div>

        <!-- 输出信息组件 -->
        <div class="divOutput">
            <h2>
                <div style="margin-top: 10px;margin-left: 10px;">
                    <font size=3 color="#000">实时检测日志：</font>
                </div>
                <div class="log">
                    <div class="log_text" id='log_list'>
                        <div id="log_text">
                            sqlite3ExprCodeRunJustOnce<br>
                            sqlite3AlterFinishAddColumn<br>
                            fts5VocabInstanceNewTerm<br>
                            fts5ExprPhraseFree.part.821<br>
                            sqlite3VtabDisconnect<br>
                            fts5TriTokenize<br>
                            __sync_val_compare_and_swap_1<br>
                            sqlite3Fts5GetVarint32<br>
                            sqlite3_deserialize<br>
                            windowFind<br>
                            sqlite3DropTable<br>
                            sqlite3TableColumnAffinity<br>
                            sqlite3ErrorFinish<br>
                            fts5VocabBestIndexMethod<br>
                            createTableStmt<br>
                            fts5ExprNodeTest_NOT<br>
                            windowAggStep<br>
                            rtreeValueUp<br>
                            sqlite3Fts5ExprClearPoslists<br>
                            sqlite3BitvecTestNotNull<br>
                            createFunctionApi<br>
                            decodeIntArray<br>
                            sqlite3Fts5ConfigParse<br>
                            fts5IndexColsetTest<br>
                            fts3RollbackToMethod<br>
                            rtreeCheckCount<br>
                            sqlite3CodeSubselect<br>
                            sqlite3Fts5ParseNode<br>
                            sqlite3ExprListSetSortOrder<br>
                            sqlite3VdbeAddOp4Int<br>
                            sqlite3VdbeFrameDelete<br>
                            whereLoopResize.part.515<br>
                            sqlite3KeyInfoOfIndex<br>
                            sqlite3_set_authorizer<br>
                            rtreeInsertCell<br>
                            rtreeCheckAppendMsg<br>
                            fts5WriteFlushBtree.part.878<br>
                            sqlite3StrAccumEnlarge.part.513<br>
                        </div>
                    </div>
                </div>
            </h2>
        </div>
        
    </div>

    <div>
            <el-button class="buttonDiv">wenjian shanchuan </el-button>
    </div>
</template>

<script>
import service from '@/utils/request';
export default {
    
    data() {
        return {
            ws: null, // WebSocket 实例
            reconnectTimeout: null,
            processNum: 0, // ProcessBar
            IfLogin: 1,           // 登录状态：0表示未登录，1表示已登录

            Ifmanager: 0,    // 权限信息：0表示是普通用户，1表示管理员用户

            username: "",   // 用户名：记录本次登录的用户名

            fileList: [],		   // 上传的文件列表

            mode: {},       // 上传的文件

            fileid: '',               //上传文件的id

            stepLine: 1,       // 当前执行完的步骤

            dis: [false, false, false, false],   // 5个按钮的disable值, false代表该按钮可用

            headers: { 'Content-Type': 'multipart/form-data' },

            loadingData: [{      // 按钮的信息
                id: 0,
                loading: false,
                text: '确认上传',
                description: '上传二进制文件按钮信息'
            }, {
                id: 1,
                loading: false,
                text: '运行IDA',
                description: '运行IDA按钮信息'
            }, {
                id: 2,
                loading: false,
                text: '生成TFRecord',
                description: '生成TFRecord按钮信息'
            }, {
                id: 3,
                loading: false,
                text: '开始测试',
                description: '开始测试按钮信息'
            }, {
                id: 4,
                loading: false,
                text: '查看结果',
                description: '查看测试结果信息'
            }, {
                id: 5,
                loading: false,
                text: '选择模型',
                description: '选择测试的模型'
            }],
        }
    },

    mounted() {
        this.connectWebSocket();
    },
    unmounted() {
        this.ws.close();
    },

    methods: {
        testLogin() {			// 检测是否登录
            service.post('http://localhost/hvdp/myphp/testLogin.php').then(res => {
                if (res.data == "#0") {
                    this.IfLogin = 1;
                } else {
                    this.IfLogin = 1;
                    this.username = res.data.split("#")[0];
                    this.Ifmanager = res.data.split("#")[1];
                }
            })
        },
        //*****************************************************************************************
        // BeforeUnplad(file, fileList){    // 上传前的操作 未登录不能上传
        //     if(this.IfLogin==0){
        //         alert("上传失败--未登录！");
        //         return false
        //     }
        // },
        handleChange(file, fileList) { // 文件数量改变
            this.fileList = fileList;
        },
        modeUpload(val) {
            this.mode = val.file;
        },
        uploadFile() { 					  // 确认上传，将文件信息上传数据库，并将文件保存至服务端
            this.$refs.uploadRef.submit()
        },
        uploadSuccess() {
            this.ws.send("from frontend");
            this.processNum = 1;
            // create the connection of webscoekt
        },

        connectWebSocket () {
            let that = this;
            that.ws = new WebSocket("ws://localhost:8080/websocket");
            that.ws.onopen = () => {
                console.log("WebSocket 连接已建立");
            };

            that.ws.onmessage = (event) => {
                console.log(event.data);
                if (event.data == '2' || event.data == '3' || event.data == '4') {
                    that.processNum = event.data; // 接收到服务器推送的消息
                } else {
                    console.log("Received unexpected info: " + event.data);
                }
            };

            that.ws.onerror = (error) => {
                console.error("WebSocket 发生错误", error);
            };

            that.ws.onclose = (event) => {
                console.log("WebSocket 连接已关闭", event.code);
                handleReconnect(); // WebSocket 连接关闭时尝试重连
            };

            // 处理 WebSocket 连接断开后的重连
            const handleReconnect = () => {
                // 如果已经在重连，避免重复重连
                if (that.reconnectTimeout) {
                    return;
                }

                that.reconnectTimeout = setTimeout(() => {
                    console.log("正在尝试重新连接 WebSocket...");
                    connectWebSocket();
                    that.reconnectTimeout = null; // 重连后清除重连超时
                }, 5000); // 5 秒后重连
            }
        },
            // if (this.IfLogin == 0) {
            //     alert("请登录后进行操作");
            // } else {
            //     if (this.fileList.length == 0) {
            //         alert("输入为空");
            //     } else {
            //         let fd = new FormData();		    // 传输文件要new FormData
            //         fd.append('file', this.mode);   // 文件信息
            //         console.log(this.mode);
            //         // fd.append('username', this.username);    // 与用户名关联
            //         this.loadingData[0].loading = true;
            //         this.loadingData[0].text = '上传中';
            //         service.post("http://localhost:8080/vulnerability/VulUpload/upload", fd).then(res => {
            //             console.log(res.data);
            //             if (res.data == -1) {
            //                 alert('上传文件格式错误--未发现包含二进制文件');
            //                 this.loadingData[0].loading = false;
            //                 this.loadingData[0].text = '确认上传';
            //                 this.fileList = [];
            //             }
            //             else {
            //                 this.loadingData[0].loading = false;
            //                 this.loadingData[0].text = '已上传';
            //                 this.stepLine = 2;
            //                 this.dis[0] = true;
            //                 // alert(res.data);
            //                 this.fileid = res.data.split('"')[1];
            //                 alert("上传成功");
            //                 // alert(this.fileid);
            //             }
            //         })
            //     }
            // }
        // },
        //**************************************************************************************************
        // socket(step) {			// 按照步骤执行相应操作client客户端发送请求，端口为8888
        //     if (this.IfLogin == 0) {
        //         alert("请登录后进行操作");
        //     } else {
        //         if (step - this.stepLine > 10) {
        //             alert("请勿跳过之前的步骤");
        //         } else {
        //             var params = new URLSearchParams();
        //             params.append('step', step);
        //             this.loadingData[step - 2].loading = true;
        //             this.loadingData[step - 2].text = '执行中';
        //             service.post('http://localhost/hvdp/myphp/socket.php', params).then(res => {
        //                 this.loadingData[step - 2].loading = false;
        //                 this.loadingData[step - 2].text = '已执行';
        //                 this.dis[step - 2] = true;
        //                 if (this.stepLine++ > 5)
        //                     this.stepLine = 0;
        //             })
        //         }
        //     }
        // },
        buttonType(val) {		//根据当前所在步骤动态改变按钮状态
            if (this.stepLine > val + 1) {
                return "success";
            }
            else {
                return "primary";
            }
        },
        selectModel() {
            if (this.IfLogin == 0) {
                alert("请登录后进行操作");
            } else {
                window.open('http://localhost/hvdp/myhtml/selectmodel.html');
            }
        },
        result() {      //查看测试结果
            if (this.IfLogin == 0) {
                alert("请登录后进行操作");
            } else {
                if (this.stepLine <= 5) {
                    alert("请勿跳过之前的步骤");
                } else {
                    var params = new URLSearchParams();
                    params.append('fileid', this.fileid);

                    service.post('http://localhost/hvdp/myphp/result.php', params).then(res => {
                        window.open('http://localhost/hvdp/myhtml/result.html?input=' + res.data, "_self");
                    })
                }
            }
        },
        logout() {				//注销登录
            service.post('http://localhost/hvdp/myphp/logout.php').then(res => {
                location.reload();
            })
        },
    }
}
</script>

<style>
body {
    margin: 0;
}

.divStep {
    margin-top: 20px;
}

.divButton div {
    text-align: center;
    display: inline-block;
    width: 16.45%;
}

.divUpload {
    margin-top: 20px;
    margin-left: 2%;
    text-align: center;
}

.divUpload h1 {
    width: 45%;
    height: 500px;
    min-width: 550px;
    border: 3px solid;
    border-color: #DCDFE6;
    position: absolute;
}

.divUploadDemo {
    margin-top: 50px;
    text-align: center;
}

.divOutput {
    margin-left: 52.5%;
}

.divOutput h2 {
    width: 45%;
    height: 500px;
    min-width: 550px;
    border: 3px solid;
    border-color: #DCDFE6;
    position: absolute;
}

.log {
    width: 97%;
    height: 370px;
    background-color: #f5f5f5;
    margin: 0 auto;
    margin-top: 10px;
    padding-top: 30px;
    padding-bottom: 40px;
}

.log_text {
    height: 370px;
    margin-left: 20px;
    font-size: 14px;
    color: #111111;
    overflow-x: hidden;
    overflow-y: auto;
}
</style>